package com.mrd.gtimp.registered;

import com.mrd.constant.MsgConstants;
import com.mrd.constant.RoleConstants;
import com.mrd.constant.SystemConstants;
import com.mrd.exception.QueryException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.config.web.json.annotation.JField;
import com.mrd.framework.config.web.json.annotation.Json;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.FilterGroupOption;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.gtimp.base.entity.Company;
import com.mrd.gtimp.base.entity.Dept;
import com.mrd.gtimp.base.entity.Role;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.base.service.CompanyBiz;
import com.mrd.gtimp.base.service.DeptBiz;
import com.mrd.gtimp.base.service.RoleBiz;
import com.mrd.gtimp.base.service.UserBiz;
import com.mrd.gtimp.business.entity.RegisteredCompany;
import com.mrd.gtimp.business.service.FundAccountBiz;
import com.mrd.gtimp.business.service.RegisteredCompanyBiz;
import com.mrd.gtimpframe.entity.CompanyInfo;
import com.mrd.gtimpframe.service.impl.CompanyInfoServiceImpl;
import com.mrd.util.KeyGenerator;
import com.mrd.util.LoginUtil;
import com.mrd.util.ReflectUtil;
import com.mrd.util.endecrypt.MD5Util;
import com.mrd.util.sendEmail.SendEmail;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.mrd.util.AdminUtil.checkRight;

/**
 * 注册审核
 * @author lenovo
 */
@Controller
@RequestMapping("/registered")
public class ApproveRegAction {

	private static final long		serialVersionUID	= -8431549015818317754L;

	@Resource
	private RegisteredCompanyBiz	registeredCompanyBiz;
	@Resource
	private CompanyBiz				sysCompanyBiz;
	@Resource
	private DeptBiz					sysDeptBiz;
	@Resource
	private UserBiz					sysUserBiz;
	@Resource
	private RoleBiz					roleBiz;
	@Resource
	private FundAccountBiz fundAccountBiz;
	@Resource
	private CompanyInfoServiceImpl companyInfoServiceImpl;

	/**
	 * 主页面
	 */
	@RequestMapping("/approve-main")
	public String main() {
		return "/gtimp/registered/approveRegMain";
	}

	@RequestMapping("/approve-platformMain")
	public String platformMain() {
		return "/gtimp/registered/platformApproveMain";
	}

	/**
	 * 审核界面
	 */
	@RequestMapping("/approve-approveRegPage")
	public String approveRegPage(String reg_company_id,HashMap map) {
		map.put("reg_company_id", reg_company_id);
		return "/gtimp/registered/approveRegEdit";
	}

	/**
	 * 平台审核界面
	 */
	@RequestMapping("/approve-platformApprove")
	public String platformApprove(String reg_company_id,Model model) {
		model.addAttribute("reg_company_id", reg_company_id);
		return "/gtimp/registered/platformApproveEdit";
	}

	@Value("${APPROVE_EMAIL_URL}")
	private String APPROVE_EMAIL_URL;

	/**
	 * 发送审核邮件
	 */
	@RequestMapping("/approve-sendApproveEmail")
	public void sendApproveEmail(String approveType,String email,String approveResult,String userId,
	        String account,RegisteredCompany registeredCompany) {
		String body = "";
		String title = "报关一线通平台注册审核结果";
		String url = APPROVE_EMAIL_URL + "?activate=" + userId;
		try {
			if("CC".equals(approveType)) {
				if("1".equals(approveResult)) {// 报关行审核不通过邮件
					body = "很遗憾，您没有通过在线报关下单平台注册审核！原因如下：" + registeredCompany.getApprove_result();
				} else {
					body = "您好：\n      恭喜您，通过了在线报关下单平台推荐报关行审核！现在在线报关平台正在对您的注册资料进行审核！\n";
				}
			} else if("CM".equals(approveType)) {
				if("0".equals(approveResult)) {// 平台管理员审核通过23
					body = "您好：\n      恭喜您，通过了在线报关下单平台注册审核！\n" + "      管理员账号为：" + account
					        + " 密码为：123\n      为了账户安全请您及时更改原始密码。谢谢！\n" + "点击以下激活链接，以激活您的账号：\n" + url
					        + "\n(如果不能点击该链接地址，请复制并粘贴到浏览器的地址输入框)\n\n\n" + "此邮件为系统所发，请勿直接回复。";
				} else if("1".equals(approveResult)) {// 平台管理员审核不通过
					body = "很遗憾，您没有通过在线报关下单平台注册审核！原因如下："
					        + registeredCompany.getPlatform_approve_result();
				}
			}
			SendEmail.sendEmail(email, title, body);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 审核注册
	@RequestMapping("/approve-saveOrUpdate")
	@ResponseBody
	public Result saveOrUpdate(RegisteredCompany registeredCompany) {
		Result msg;
		if(checkRight(RoleConstants.SUP_CUSTOMER_SAVE)) {
			try {
				String companyType = LoginUtil.getLoginUser().getCompany().getType();
				if(StringUtils.isNotEmpty(registeredCompany.getReg_company_id())) { // 新增操作
					List<String> properties = new ArrayList<String>();
					if("CC".equals(companyType)) {// 报关行审核
						properties.add("approve_status");
						properties.add("approve_time");
						properties.add("approve_person");
						properties.add("approve_result");
						registeredCompany.setApprove_time(new Date());
						registeredCompanyBiz.updateEntity(registeredCompany, properties);
						sendApproveEmail(companyType, registeredCompany
						        .getCom_email(), registeredCompany
						                .getApprove_status(), "", "", registeredCompany);
					} else if("CM".equals(companyType)) {// 平台审核
						properties.add("platform_approve_status");
						properties.add("platform_approve_time");
						properties.add("platform_approve_person");
						properties.add("platform_approve_result");
						registeredCompany
						        .setPlatform_approve_person(LoginUtil.getLoginUser().getAccount());
						registeredCompany.setPlatform_approve_time(new Date());
						registeredCompanyBiz.updateEntity(registeredCompany, properties);
						if("0".equals(registeredCompany.getPlatform_approve_status())) {
							User sysUser = new User();
							List<User> userList = new ArrayList<User>();
							String account = "admin@" + ((int) (Math.random() * 1000) + 1000)
							        + KeyGenerator.generateNoFromDate("HHmmss");
							sysUser.setId(null);
							sysUser.setName(account);
							sysUser.setAccount(account);
							sysUser.setPwd(MD5Util.string2MD5("123"));// 默认密码123
							sysUser.setMobile(registeredCompany.getCom_link_phone());
							sysUser.setType("1");
							sysUser.setIsabled("1");// 未激活
							sysUser.setState("0");
							sysUser.setCtime(new Date());
							sysUser.setEmail(registeredCompany.getCom_email());
							sysUser.setMvalidate("1");
							sysUser.setTelphone(registeredCompany.getCom_link_phone());
							List<Role> roleList = new ArrayList<Role>();
							Role role = null;
							if("CC".equals(registeredCompany.getCom_type())) {
								role = roleBiz.findEntityById("f0fc943258f1574c0158f24e4f5f00cf");// 报关公司管理ID
							} else if("CL".equals(registeredCompany.getCom_type())) {
								role = roleBiz.findEntityById("f0fc943258f1574c0158f24ffd8900d9");// 客户公司管理ID
							}
							roleList.add(role);
							sysUser.setRoles(roleList);
							sysUserBiz.saveOrupdateEntity(sysUser);
							userList.add(sysUser);

							Dept sysDept = new Dept();
							sysDept.setId(null);
							sysDept.setName("管理员部门");
							sysDept.setUsers(userList);
							sysDept.setIsabled("1");// 未激活
							sysDept.setState("0");
							sysDept.setCtime(new Date());
							sysDeptBiz.saveOrupdateEntity(sysDept);

							Company entity = new Company();
							entity.setId(null);
							entity.setName(registeredCompany.getCom_name());
							entity.setAddress(registeredCompany.getCom_address());
							entity.setFax(registeredCompany.getFax());
							entity.setType(registeredCompany.getCom_type());
							entity.setPort(registeredCompany.getService_port());
							entity.setPort_code(registeredCompany.getService_port_code());
							entity.setValidate("1");
							entity.setIsabled("1");// 未激活
							entity.setState("0");
							entity.setCtime(new Date());
							entity.setCom_customs_code(registeredCompany.getCom_customs_code());
							entity.setCom_code(registeredCompany.getCom_code());
							Set<Dept> depts = new HashSet<Dept>();
							depts.add(sysDept);
							entity.setDepts(depts);
							sysCompanyBiz.saveOrupdateEntity(entity);
							sendApproveEmail(companyType, registeredCompany.getCom_email()
							        .trim(), registeredCompany.getPlatform_approve_status(), sysUser
							                .getId(), account, registeredCompany);

							List<Object> list = sysCompanyBiz.findObjectBySql("select com_id from T_SYS_COMPANY where com_name=:com_name",0,1,new HashMap<String,Object>(){
								{
									put("com_name",entity.getName());
								}
							});
							if(list.size()!=1){
								throw new Exception("初始化账号出错！");
							}


							fundAccountBiz.initFundAccount(list.get(0).toString());

							//构建公司信息实体, 保存委托关系, 保存联系人
							companyInfoServiceImpl.saveComInfoFormSysCompany(entity, registeredCompany);
						} else if("1".equals(registeredCompany.getPlatform_approve_status())) {
							sendApproveEmail(companyType, registeredCompany
							        .getCom_email(), registeredCompany
							                .getPlatform_approve_status(), "", "", registeredCompany);
						}
					}
				}
				msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
			} catch (Exception e) {
				e.printStackTrace();
				msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
			}
			return msg;
		}
		return Result.newFailInstance(SystemConstants.ROLE_FAIL);
	}

	@RequestMapping("/approve-find")
	@ResponseBody
	public RegisteredCompany find(RegisteredCompany registeredCompany) {
		if(null != registeredCompany
		        && StringUtils.isNotEmpty(registeredCompany.getReg_company_id())) {
			try {
				registeredCompany = registeredCompanyBiz
				        .findEntityById(registeredCompany.getReg_company_id());
				return registeredCompany;
			} catch (QueryException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@RequestMapping("/approve-findList")
	@ResponseBody
	@Json({@JField("reg_company_id"), @JField("com_name"), @JField("com_code"),
	        @JField("com_customs_code"), @JField("com_link_person"), @JField("com_link_phone"),
	        @JField("com_email"), @JField("customs_broker"), @JField("customs_broker_id"),
	        @JField("approve_status"), @JField("reg_time"), @JField("platform_approve_status") })
	public Page<RegisteredCompany> findList(Jqgrid jqgrid,HttpServletRequest request) {
		Filter filters = jqgrid.getFilters();
		int count;
		List<RegisteredCompany> registeredCompanyDtos = new ArrayList<>();
		try {
			if(null == filters) {
				filters = new Filter();
				filters.setGroupOp(FilterGroupOption.AND);
			}
			String companyId = LoginUtil.getLoginUser().getCompany().getId();
			String companyType = LoginUtil.getLoginUser().getCompany().getType();
			String hql = "from com.mrd.gtimp.business.entity.RegisteredCompany registeredCompany where 1=1";
			String hqlCount = "select count(*) from com.mrd.gtimp.business.entity.RegisteredCompany registeredCompany where 1=1";
			String whereCase = "";
			if("CC".equals(companyType)) {// 供应商公司类型
				whereCase = whereCase + " and registeredCompany.customs_broker_id = '" + companyId
				        + "'";
			}
			if(filters.getRules() != null && filters.getRules().size() > 0) {
				for(SearchRule sr : filters.getRules()) {
					String field = sr.getField();
					Object data = sr.getData();
					Field f = ReflectUtil.getField(sr.getField(), RegisteredCompany.class);
					boolean isDate = false;
					if(f != null) {
						if(f.getType().equals(Date.class)) {
							data = "to_date('" + data + "','yyyy-MM-dd')";
							isDate = true;
						}
					}
					if(sr.getOp().equals(SearchRuleOption.eq)) {
						whereCase = whereCase + " and registeredCompany." + field + " = '" + data
						        + "' ";
					} else if(sr.getOp().equals(SearchRuleOption.nc)) {
						whereCase = whereCase + " and registeredCompany." + field + " not in ('"
						        + data + "') ";
					} else if(sr.getOp().equals(SearchRuleOption.gt)) {
						whereCase = whereCase + " and registeredCompany." + field
						        + (isDate ? " > " + data : " > '" + data + "'");
					} else if(sr.getOp().equals(SearchRuleOption.lt)) {
						whereCase = whereCase + " and registeredCompany." + field
						        + (isDate ? " < " + data : " < '" + data + "'");
					} else if(sr.getOp().equals(SearchRuleOption.ge)) {
						whereCase = whereCase + " and registeredCompany." + field
						        + (isDate ? " >= " + data : " >= '" + data + "'");
					} else if(sr.getOp().equals(SearchRuleOption.le)) {
						whereCase = whereCase + " and registeredCompany." + field
						        + (isDate ? " <= " + data : " <= '" + data + "'");
					} else {
						whereCase = whereCase + " and registeredCompany." + field + " like '%"
						        + data + "%' ";
					}
				}
			}

			// Order order = new Order();
			// if (null != sidx && !"".equals(sidx)) {
			// order.add(sidx, sord);
			// }
			// for (String key : order.keySet()) {
			// whereCase = whereCase + " order by registeredCompany." + key + " "
			// + (order.get(key) ? "desc" : "asc") + " ";
			// }
			whereCase = whereCase + " order by registeredCompany." + request.getParameter("sidx")
			        + " " + request.getParameter("sord") + " ";
			count = registeredCompanyBiz.findEntityCount();
			count = registeredCompanyBiz.findEntityCountByHql(hqlCount + whereCase, null);
			registeredCompanyDtos = registeredCompanyBiz
			        .findEntityByHql(hql + whereCase, jqgrid.getPage().getPageNumber() + 1, jqgrid
			                .getPage().getPageSize(), filters);
			Page<RegisteredCompany> page = new PageImpl<>(registeredCompanyDtos, jqgrid
			        .getPage(), count);
			if(page.getSize() > 0) {
				return page;
			}
		} catch (QueryException e) {
			e.printStackTrace();
		}
		return null;
	}

}
